package br.com.siscov.control.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import br.com.siscov.control.form.LogarForm;
import br.com.siscov.model.login.service.LoginService;
import br.com.siscov.model.vo.LoginVo;
import br.com.siscov.util.Constantes;

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ActionErrors errors = new ActionErrors();
		ActionForward forward = new ActionForward();
		try {

			LogarForm loginForm = (LogarForm) form;

			
			LoginVo loginVo = loginForm.populaVO();

			// LoginService.obterLogin(loginVo);
			if (LoginService.autenticaUsuario(loginForm.getLogin(), loginForm.getSenha())) {
				LoginVo login = LoginService.obterAcesso(loginVo);
				request.getSession().setAttribute(Constantes.SESSAO_LOGIN, login);
				
				if (login.getTipo() == 1) {
					forward = mapping.findForward(Constantes.FORWARD_SUCESSO);

				} else {
					forward = mapping.findForward(Constantes.FORWARD_SUC_GER);
				}
				return forward;
			}

						
		} catch(Exception e) {
			return forward;
		}
		errors.add("errors", new ActionMessage("errors.login.invalido.exception"));
		saveErrors(request, errors);
		return mapping.findForward(Constantes.FWD_ERRO);
		
	}
}